/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session04;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

/**
 *
 * @author cibervn
 */
public class Decrypt {

    private static Scanner keyboard = new Scanner(System.in);

    public static void main(String[] args) {
        try {
            //Declaration
            String fileEncrypted;
            String fileDecrypted;

            //Input
            System.out.println("File to decrypt:");
            fileEncrypted = keyboard.nextLine();

            System.out.println("file to save:");
            fileDecrypted = keyboard.nextLine();

            System.out.print("Enter your password:");
            char[] password = keyboard.nextLine().toCharArray();

            //Init
            byte[] salt = {
                (byte) 0x12, (byte) 0x32, (byte) 0x12, (byte) 0x56,
                (byte) 0x12, (byte) 0x32, (byte) 0x12, (byte) 0x56
            };
            int count = 20;

            PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, count);

            PBEKeySpec keySpec = new PBEKeySpec(password);
            
            SecretKeyFactory keyFactor = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
            
            SecretKey sk = keyFactor.generateSecret(keySpec);

            decrypt(fileEncrypted, fileDecrypted, sk, parameterSpec);

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }

    private static String decrypt(String encryptedFile, String decryptedFile, SecretKey sk, PBEParameterSpec parameterSpec) {
        try {
            //Input
            DataInputStream dis = new DataInputStream(new FileInputStream(encryptedFile));
            String line = dis.readUTF();
            byte[] encrypted = Base64.decode(line);
            dis.close();
            
            //Getting cipher
            Cipher c = Cipher.getInstance("PBEWithMD5AndDES");
            //Init
            c.init(Cipher.DECRYPT_MODE, sk, parameterSpec);
            //Encrypt
            byte[] decrypted = c.doFinal(encrypted);

            //Save
            PrintWriter pw = new PrintWriter(decryptedFile);
            pw.print(new String(decrypted));
            pw.close();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return null;
    }
}
